<template>
  <div ref="messageContainer" class="message-container">
    <MessageArea
      title="留言板"
      :total="data.total"
      :list="data.rows"
      @submit="handleSubmit"
      :isListLoading="isLoading"
      :text="text"
    ></MessageArea>
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import fetchData from "@/mixins/fetchData";
import * as mesApi from "@/api/message";
import mainScroll from "@/mixins/mainScroll";
export default {
  mixins: [fetchData({ total: 0, rows: [] }), mainScroll("messageContainer")],
  data() {
    return {
      text: "",
      limit: 10,
      page: 1,
    };
  },
  created() {
    this.$eventBus.$on("mainScroll", this.handleNextPage);
  },
  destoryed() {
    this.$eventBus.$off("mainScroll", this.handleNextPage);
  },
  components: {
    MessageArea,
  },
  computed: {
    hasMore() {
      return this.data.rows.length >= this.data.total;
    },
  },
  methods: {
    async fetchData() {
      return await mesApi.getMessages(this.page, this.limit);
    },
    async handleSubmit(formData, callback) {
      const resp = await mesApi.postMessage({ ...formData });
      if (!resp) {
        callback("您的操作过于频繁，请稍后再试", "info");
      } else {
        //   this.data.rows.unshift(resp);
        this.data.total++;
        this.data = await mesApi.getMessages(this.page, this.page * this.limit);
        callback("感谢您的留言");
      }
    },
    handleNextPage(dom) {
      if (this.isLoading || !dom) {
        return;
      }
      let range = 100;
      let dec = Math.abs(dom.scrollTop + dom.clientHeight - dom.scrollHeight);
      if (dec <= range) {
        this.fetchMore();
      }
    },
    async fetchMore() {
      if (this.data.rows.length === 0) {
        this.text = "-------博主很菜，请大佬们给点建议------";
        return;
      }
      if (this.hasMore) {
        this.text = "-------我也是有底线的-------";
        return;
      }
      this.isLoading = true;
      this.page++;
      let resp = await this.fetchData();
      this.data.rows = this.data.rows.concat(resp.rows);
      this.isLoading = false;
    },
  },
};
</script>

<style scoped lang="less">
.message-container {
  width: 100%;
  height: 100%;
  padding: 20px 0;
  box-sizing: border-box;
  overflow-y: auto;
  scroll-behavior: smooth;
}
.message-area-container {
  width: 700px;
  margin: 0 auto;
}
</style>